package yxy.game.pm2.command.infinite;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.InfiniteMessage;
import yxy.game.pm2.module.infinite.RankInfinite;
import yxy.game.pm2.module.player.PlayerHandle;

import java.util.Collection;

/** 神将试炼 神将试炼排行榜 */
@MessageType(proto = Command.InfiniteRank, classtype = InfiniteMessage.InfiniteRankRequest.class)
public class CMD_InfiniteRank extends Command<InfiniteMessage.InfiniteRankRequest> {

	@Override
	public void execute(MessageSource messageSource, InfiniteMessage.InfiniteRankRequest request) {
		String playerCode = messageSource.getTag();

		InfiniteMessage.InfiniteRankResponse.Builder response = InfiniteMessage.InfiniteRankResponse.newBuilder();

		RankInfinite rankInfinite = RankInfinite.getRank(playerCode);
		try {
			Collection<RankEntry> top = rankInfinite.top(rankInfinite.topSize());
			int rank = 0;
			for (RankEntry entry : top) {
				String pCode = entry.getKey();
				int best = entry.getValue().intValue();

				InfiniteMessage.RankInfinite.Builder builder = InfiniteMessage.RankInfinite.newBuilder();
				builder.setRank(++rank);
				builder.setPlayerInfo(new PlayerHandle().playerSimpleInfo(pCode));
				builder.setBest(best);
				response.addRank(builder);
			}

			{
				int playerRank = 0;
				int best = 0;
				RankEntry entry = rankInfinite.get(playerCode);
				if (entry != null) {
					playerRank = rankInfinite.rank(playerCode);
					best = entry.getValue().intValue();
				}

				InfiniteMessage.RankInfinite.Builder builder = InfiniteMessage.RankInfinite.newBuilder();
				builder.setRank(playerRank);
				builder.setPlayerInfo(new PlayerHandle().playerSimpleInfo(playerCode));
				builder.setBest(best);
				response.setMy(builder);
			}
			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, InfiniteMessage.InfiniteRankResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}